<?php

/**
 * @filesource Communicates with the Student control file to know which student
 * data to get and set. It is the only file that has the SQL queries and MySQL
 * connections
 *
 * @copyright 2011 by Dan, Steven, Brice, Mike, and Aaron.  This program is part
 * of Internship 2 Career, which is free software. It comes with absolutely no
 * warranty. You can redistribute or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation (For
 * more information, see <http://www.gnu.org/licenses/).
 *
 * @version February 10, 2011
 *
 * @author Mike Tierney, Brice Rader and Aaron Jarzombeck
 */
/**
 * This is the database file.
 * It controls the internship file to list all internships and
 * to add or delete an internship into the database.
 * It is the only file that has the SQL queries and MySQL connections
 *
 */

class dbInternship {

    private $db;

	/**
	* Table template
	*/
    static function createTable() {
        //Create table internship
        $query = "
            create table internship(
                internshipID            int             NOT NULL AUTO_INCREMENT,
                opportunityID           int             NOT NULL,
                studentID               int             NOT NULL,
                hours                   varchar(25)	NULL,
                special                 varchar(10)	NULL,
                semester                varchar(25)     NULL,
                constraint PK_Contact PRIMARY KEY (internshipID),
                constraint FK_Contact_Opportunity FOREIGN KEY (opportunityID)
                    references opportunity (opportunityID),
                constraint FK_Contact_Student FOREIGN KEY (studentID)
                    references student (studentID)
                );
    ";
        connectToDatabase();
        $result = mysql_query($query);
        echo mysql_error();
        mysql_close();
        if ($result == false) {
            return false;
        }

        //Previous query was successful.
        return true;
    }

    /**
     * Gets all the internships from the database.
     * @return object Returns MySQL data object
     */
    function getAllInternships() {
        $query = "SELECT * FROM internship";
        connectToDatabase( );
        $result = mysql_query($query);
        mysql_close();
        if ($result == false) {
            echo mysql_error( );
            return false;
        }

        //Query was successful.
        return $result;
    }

    /**
     * Updates internship information.
     * @param object $i Class Contact
     * @return int Returns 0 if there was an error updating, else returns 1
     */
    function updateInternship($i) {
        $internshipID = $i->getInterhshipID();
        $opportunityID = $i->getOpportunityID();
        $studentID = $i->getStudentID();
        $hours = $i->getHours();
        $special = $i->getSpecial();
        $semester = $i->getSemester();

        if ($intershipID == '') {
            return false;
        } else {
            if ($opportunityID != '') {
                if (!mysql_query("UPDATE internship SET opportunityID=
                        '$opportunityID' WHERE internshipID=$internshipID"))
                    die("Could not update internship with ID = $internshipID");
            }
            if ($studentID != '') {
                if (!mysql_query("UPDATE internship SET studentID='$studentID'
                        WHERE internshipID=$internshipID"))
                    die("Could not update internship with ID = $internshipID");
            }
            if ($hours != '') {
                if (!mysql_query("UPDATE internship SET hours='$hours' WHERE
                        internshipID=$internshipID"))
                    die("could not update internship with ID = $internshipID");
            }
            if ($special != '') {
                if (!mysql_query("UPDATE internship SET special='$special' WHERE
                        internshipID=$internshipID"))
                    die("could not update internship with ID = $internshipID");
            }
            if ($semester != '') {
                if (!mysql_query("UPDATE internship SET semester='$semester'
                        WHERE internshipID=$internshipID"))
                    die("could not update internship with ID = $internshipID");
            }

            return true;
        }
    }

    /**
     * Deletes a internship from the database.
     * @param object $i Class Internship
     * @return bool Returns TRUE if contact can be deleted.
     */
    function deleteInternship($i) {
        if (!$i instanceof Internship) {
            echo ("Invalid argument deleteFrom( ) function<br />");
            return false;
        }

        //Compose the DELETE FROM query string.
        $query = sprintf("DELETE FROM internship WHERE internshipID = %d",
                        $i->getInternshipID()
        );
        connectToDatabase( );
        $result = mysql_query($query);
        mysql_close( );
        if ($result == false) {
            echo mysql_error( );
            return false;
        }

        //Query was successful.
        return true;
    }

    /**
     * Adds a internship to the database.
     * @param object $i Class Internship
     * @return bool Returns TRUE if query completes successfully.
     */
    static function addInternship($i, &$id) {
        if (!$i instanceof internship) {
            echo ("Invalid arguement insertInto ( ) function<br />");
            return false;
        }
        //Compose the INSERT INTO query srting. Primary key value is missing.
        //Database server automatically generates a unique ID for the primary
        //key.
        $query = sprintf("INSERT INTO internship VALUES (null, %d, %d, '%s',
            '%s', '%s')",
                        $i->getOpportunityID(),
                        $i->getStudentID(),
                        $i->getHours(),
                        $i->getSpecial(),
                        $i->getSemester()
        );
        connectToDatabase( );
        $result = mysql_query($query);
        $id = mysql_insert_id();
        mysql_close( );
        if ($result == false) {
            echo mysql_error ( );
            return false;
        }
        //query was successful.
        printf("Internship added has id %d\n<br />", mysql_insert_id());
        return true;
    }

    /**
     * Checks to see if the ID exists.
     * @param object $i Class Internship
     * @return int Returns FALSE if ID cannot be found, and TRUE if ID is found
     */
    function checkID($i) {
        if (!($i instanceof Internship)) {
            return false;
        }
        $internshipID = $i->getIntnershipID();
        connectToDatabase();
        if (mysql_num_rows(mysql_query("SELECT * FROM internship WHERE
                internshipID=$internshipID")) == false) {
            mysql_close();
			//nothing exists
            return false;
        } else {
            return true;
        }
    }

    /**
     * Gets all the internship information for a internship with a certain ID.
     * @param int $internshipID ID of internship you want to get.
     * @return object Returns 0 if ID does not exist, or a Contact object
     * if it does
     */
    function getInternship($internshipID) {

        $result = mysql_query("SELECT * FROM internship WHERE internshipID=
                $internshipID");
        if (!$result) {
            return false; //id does not exist
        } else {
            $row = mysql_fetch_assoc($result);
            $i->setIntenrshipID($internshipID);
            $i->setSemester($row['semester']);
            return $i;
        }
    }

    /**
     * Gets the studentid of a specified internship.
     * @param getStudentID $val
     * @return object Returns FALSE on failure, or a Internship object on
     * success
     */
    function getStudentID($val) {
        $result = mysql_query("SELECT studentID FROM internship WHERE
                internshipID='$val'");
        $row = mysql_fetch_row($result);
        return $row[0];
    }

    /**
     * Gets the opportunityID of a specified internship.
     * @param getOpportunityID $val
     * @return object Returns 0 on failure, or a Internship object on success
     */
    function getOpportunityID($val) {
        $result = mysql_query("SELECT opportunityID FROM internship WHERE
                internshipID='$val'");
        $row = mysql_fetch_row($result);
        return $row[0];
    }

    /**
     * Gets the hours of a specified internship.
     * @param getHours $internshipID
     * @return object Returns 0 on failure, or a Internship object on success
     */
    function getHours($internshipID) {
        $result = mysql_query("SELECT hours FROM internship WHERE
                internshipID='$val'");
        $row = mysql_fetch_row($result);
        return $row[0];
    }

    /**
     * Gets the semester of a specified internship.
     * @param getSemester $val
     * @return object Returns 0 on failure, or a Internship object on success
     */
    function getSemester($val) {
        $result = mysql_query("SELECT semester FROM internship WHERE
                internshipID='$val'");
        if (!$result) {
            return false;
        }
        $row = mysql_fetch_row($result);
        return $row[0];
    }

    /**
     * Gets the special of a specified internship.
     * @param getSpecial $val
     * @return object Returns 0 on failure, or a Internship object on success
     */
    function getSpecial($val) {
        $result = mysql_query("SELECT special FROM internship WHERE
                internshipID='$val'");
        $row = mysql_fetch_row($result);
        return $row[0];
    }

	/**
   * Gets all fields by ID
   * @param getAllByID $id
   * @return object returns all fields
   */
    public static function getAllByID($id, &$output) {
        $query = sprintf("SELECT opportunityID, studentID, hours,
            special, semester FROM internship WHERE
            internshipID=%d", $id);
        //printf("->Query: %s<br />", $query);
        connectToDatabase();
        $result = mysql_query($query);
        mysql_close();

        if ($result == false) {
            $output = sprintf("%s", mysql_error());
            return false;
        }
        //process result and print out warning or attribute values
        return dbInternship::checkForOneInstance($result, $id, $output);
    }

	/**
   * Checks for one instance
   * @param checkForOneInstance $result
   * @param checkForOneInstance $id
   */
    private static function checkForOneInstance($result, $id, &$output) {
        //Local variables are initialized.
        $errorStatus = false;

        $howMany = mysql_num_rows($result);
        switch ($howMany) {
            case 0:
                $output = sprintf("No Interhsnip instance with ID=%d was found.",
                                $id);
                $errorStatus = true;
                break;
            case 1:
                //mysql_fetch() DOES NOT return primary key values
                $output = mysql_fetch_assoc($result);
                $errorStatus = false;
                break;
            default:
                $output = sprintf("There are multiple Internship instances with
                                  ID=%d.", $id);
                $errorStatus = true;
                break;
        }
        return $errorStatus;
    }
}
?>

